import {useRef, useState} from 'react';

import cuboxPath from './cubox-path.jsx';
import useResize from './use-resize.jsx';

import * as styles from './cubox.module.css';

const Cubox = (props) => {

	const {
		cornerRadius=20,
		strokeWidth=1,

		isOutlined=false,

		backColor='#343434',
		foreColor='bisque',
    opacity=1,

    hoverBackColor,
    hoverForeColor,

    corners=['C', 'C', 'C', 'C'],
		children=<div style={{height: 30, width: 30}} />,

    className,
    style={},

    onClick,
	} = props;

  const [isHovered, setIsHovered] = useState(false);

  // Attach ref to a wrapper around the content
  const contentRef = useRef(null);
  const {size} = useResize(contentRef);

  // Use hover colors if hovered and provided, else normal
  const currentBackColor = isHovered && hoverBackColor ? hoverBackColor : backColor;
  const currentForeColor = isHovered && hoverForeColor ? hoverForeColor : foreColor;

  const pathTransition = { transition: 'fill 0.1s, stroke 0.1s' };

  const frame = isOutlined
  ? <>
      <path style={{...pathTransition, fill:currentBackColor, fillOpacity:opacity}} d={cuboxPath(size, cornerRadius, 0, corners)}/>
      <path style={{...pathTransition, fill:currentForeColor}} d={cuboxPath(size, cornerRadius, strokeWidth, corners)}/>
    </>
  : <path style={{...pathTransition, fill:currentBackColor, fillOpacity:opacity}} d={cuboxPath(size, cornerRadius, 0, corners)}/>

  const backProps = {
    viewBox: `0 0 ${size.width} ${size.height}`,
    style: {
      position:'absolute',
      top:0,
      left:0,
      width: size.width,
      height: size.height,
      zIndex: 0,
      pointerEvents: 'none', // let clicks pass through to content
    }
  }

  return <div 
    className={`${styles.cubox} ${className || ''}`}
    style={{
      position:'relative', 
      ...style
    }}
    onClick={onClick}
    onMouseEnter={() => setIsHovered(true)}
    onMouseLeave={() => setIsHovered(false)}
  >
    {(size.width > 0 && size.height > 0) && (
      <svg {...backProps}>{frame}</svg>
    )}
    <div
      ref={contentRef}
      className={styles['cubox-inner']}
      style={{position:'relative', zIndex: 1, width: '100%', height: '100%'}}
    >
      {children}
    </div>
  </div>
}

export default Cubox;